package com.dhcc.DRGsHosp.application.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Named;

import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.JdbcTemplateObj;
import org.dayatang.querychannel.QueryChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.transaction.annotation.Transactional;

import com.dhcc.DRGsHosp.application.QuotaManageApplication;
import com.dhcc.DRGsHosp.core.domain.ManageSummary;
import com.dhcc.DRGsHosp.core.domain.ManageSummaryDtl;
import com.dhcc.DRGsHosp.core.domain.QuotaManage;
import com.dhcc.DRGsHosp.infra.util.StringUtils;
/**
 * @Discription：管理目标值管理    
 * @Author：liuhongjun  
 * @ClassName: QuotaManageApplicationImpl  
 * @Date: 2018年3月25日 下午4:42:29  
 * @Version：3.1.0 DHC.DRGs
 */
@Named
@Transactional
public class QuotaManageApplicationImpl implements QuotaManageApplication {
	
	private EntityRepository repository;
	
	private QueryChannelService queryChannel;
    
    private EntityRepository getRepository() {
		if (repository == null) {
			repository = InstanceFactory.getInstance(
					EntityRepository.class, "repository") ;
		}
		return repository;
	}
    
	
    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
    
    @Autowired  
    private JdbcTemplateObj jdbcTemplateObj; 
    
    @Autowired  
    private NamedParameterJdbcTemplate jdbcTempSeverice; 
    
	public QuotaManage getQuotaManage(Double qmId) {
		return QuotaManage.get(QuotaManage.class, qmId);
	}
	
	public void creatQuotaManage(QuotaManage quotaManage) {
		quotaManage.save();
	}
	
	public void removeQuotaManage(QuotaManage quotaManage) {
		if(quotaManage != null){
			quotaManage.remove();
		}
	}
	
	public void removeQuotaManages(Set<QuotaManage> quotaManages) {
		for (QuotaManage quotaManage : quotaManages) {
			quotaManage.remove();
		}
	}
	
	public List<QuotaManage> findAllQuotaManage() {
		return QuotaManage.findAll(QuotaManage.class);
	}
	
	public List<QuotaManage> getQuotaMange(QuotaManage quotaManage){
		StringBuilder jpql = new StringBuilder("select _quotaManage from QuotaManage _quotaManage where 1=1");
		if(StringUtils.hasLength(quotaManage.getPardrgCode()) && !"DRG_DHCC".equals(quotaManage.getPardrgCode())){
			jpql.append(" and _quotaManage.pardrgCode='"+quotaManage.getPardrgCode()+"'");
			jpql.append(" and _quotaManage.parDepCode is null ");
			jpql.append(" and _quotaManage.parDepGroupCode is null");
		}else if(StringUtils.hasLength(quotaManage.getParDepCode()) && !"DRG_DHCC".equals(quotaManage.getParDepCode())){
			jpql.append(" and _quotaManage.parDepCode='"+quotaManage.getParDepCode()+"'");
			jpql.append(" and _quotaManage.pardrgCode is null ");
			jpql.append(" and _quotaManage.parDepGroupCode is null");
		}else{
			jpql.append(" and 1>2 ");
		}
		if(StringUtils.hasLength(quotaManage.getManageYear())){
			jpql.append(" and _quotaManage.manageYear='"+quotaManage.getManageYear()+"'");
		}
		List<QuotaManage> quotaManages = getQueryChannelService().createJpqlQuery(jpql.toString()).list();
		
		return quotaManages;
	}

	/**
	 * @methodname    :getQuotaMangeM
	 * @description   : 获取医院管理目标的值
	 * @param         :
	 * @author        :lileizheng
	 * @return        :
	 * @date          :2015年7月24日
	 */
	public List<QuotaManage> getQuotaMangeM(QuotaManage quotaManage) {
		StringBuilder jpql = new StringBuilder("select _quotaManage from QuotaManage _quotaManage where 1=1");
		if(!"DRG_DHCC".equals(quotaManage.getPardrgCode())
			&& (!"DRG_DHCC".equals(quotaManage.getParDepGroupCode()))
			){
			jpql.append(" and _quotaManage.pardrgCode='"+quotaManage.getPardrgCode()+"'");
			jpql.append(" and _quotaManage.parDepCode is null ");
			jpql.append(" and _quotaManage.parDepGroupCode ='"+quotaManage.getParDepGroupCode()+"'");
		}else if(!"DRG_DHCC".equals(quotaManage.getPardrgCode())
			&& !"DRG_DHCC".equals(quotaManage.getParDepCode())
			){
			jpql.append(" and _quotaManage.parDepCode='"+quotaManage.getParDepCode()+"'");
			jpql.append(" and _quotaManage.pardrgCode = '"+quotaManage.getPardrgCode()+"' ");
			jpql.append(" and _quotaManage.parDepGroupCode is null");
		}else if("DRG_DHCC".equals(quotaManage.getPardrgCode())
			&& !"DRG_DHCC".equals(quotaManage.getParDepGroupCode())
			){
			jpql.append(" and _quotaManage.pardrgCode is null ");
			jpql.append(" and _quotaManage.parDepCode is null ");
			jpql.append(" and _quotaManage.parDepGroupCode ='"+quotaManage.getParDepGroupCode()+"'");
		}else if("DRG_DHCC".equals(quotaManage.getPardrgCode())
			&& !"DRG_DHCC".equals(quotaManage.getParDepCode())
			){
			jpql.append(" and _quotaManage.parDepCode='"+quotaManage.getParDepCode()+"'");
			jpql.append(" and _quotaManage.pardrgCode is null ");
			jpql.append(" and _quotaManage.parDepGroupCode is null");
		}else{
			jpql.append(" and 1>2 ");
		}
		if(StringUtils.hasLength(quotaManage.getManageYear())){
			jpql.append(" and _quotaManage.manageYear='"+quotaManage.getManageYear()+"'");
		}
		List<QuotaManage> quotaManages = getQueryChannelService().createJpqlQuery(jpql.toString()).list();
		
		return quotaManages;
	}
	
	@Override
	public void saveManageSummary(ManageSummary manageSummary) {
		int num = judgeManage(manageSummary) ;
		if( num == 0 ) {
			manageSummary.save() ;
		} else {
			StringBuffer sql = new StringBuffer() ;
			sql.append(" update drgs.t_managesummary tm ") ;
			sql.append(" set tm.ms_flag = :msFlag ") ;
			sql.append(" where tm.ms_code = :msCode ") ;
			SqlParameterSource paramSource = new BeanPropertySqlParameterSource(manageSummary);
			jdbcTempSeverice.update(sql.toString(), paramSource ) ;
		}
	}

	@Override
	public void saveManageSummaryDtl(ManageSummaryDtl manageSummaryDtl) {
		manageSummaryDtl.save();
	}
	
	@Override
	public void updateManageSummaryDtl(ManageSummaryDtl manageSummaryDtl) {
		StringBuffer sql = new StringBuffer() ;
		sql.append(" update drgs.t_managesummarydtl tmdtl \n") ;
		sql.append(" set tmdtl.par_ms_code = :parMsCode ,  tmdtl.parquota_code = :parquotaCode, \n") ;
		sql.append(" tmdtl.manage_benchmark = :manageBenchmark ,  tmdtl.pardrg_code = :pardrgCode , \n") ;
		sql.append(" tmdtl.std_year = :stdYear , tmdtl.patient_type = :patientType \n") ;
		sql.append(" where tmdtl.msdtl_id = :msDtlId ") ;
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(manageSummaryDtl);
		jdbcTempSeverice.update(sql.toString(), paramSource ) ;
	}
	
	@Override
	public void updateQuotaManage(QuotaManage quotaManage) {
		StringBuffer sql = new StringBuffer() ;
		sql.append(" update drgs.t_quotamanage qtm  \n") ;
		sql.append(" set qtm.pardep_code = :parDepCode ,qtm.par_ms_code = :parMsCode, \n") ;
		sql.append(" qtm.parquota_code = :parquotaCode,qtm.pardrg_code = :pardrgCode, \n") ;
		sql.append(" qtm.manage_benchmark = :manageBenchmark ,qtm.pardepgroup_code = :parDepGroupCode, \n") ;
		sql.append(" qtm.patient_type = :parPatientType, qtm.manage_year = :manageYear \n") ;
		sql.append(" where  qtm.qm_id = :qmId") ;
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(quotaManage);
		jdbcTempSeverice.update(sql.toString(), paramSource ) ;
	}

	@Override
	public int judgeManage(ManageSummary manageSummary) {
		String sql = "select count(1) cnt from drgs.T_MANAGESUMMARY ms where ms.ms_code = '"+manageSummary.getMsCode()+"'  \n";
		List<Object> cl =  getRepository().createSqlQuery(sql).list();
		return Integer.parseInt(cl.get(0).toString());
	}


	@Override
	public List<ManageSummaryDtl> findManageSummaryDtlExistingData(String parMscode) {
		String sql = "select new ManageSummaryDtl(msDtlId, parMsCode,  parquotaCode,  pardrgCode,  stdYear, patientType) from ManageSummaryDtl mdtl where mdtl.parMsCode  = :parMscode" ;
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("parMscode", parMscode) ;
		List<ManageSummaryDtl> resultList = getRepository().createJpqlQuery(sql).addParameter("parMscode", parMscode).list() ;
		return resultList;
	}

/**
 * 
 *  @Description：获取系统中目前存在的键
 *  @Author LiuHongJun  
 *  @see com.dhcc.DRGsHosp.application.QuotaManageApplication#findQutaManageAllMajorKey()
 */
	@Override
	public List<QuotaManage> findQuotaManageExistingData(String parMsCode) {
		// TODO Auto-generated method stub
		String jpql = "select new QuotaManage(qmId, parquotaCode, parDepCode, pardrgCode, parDepGroupCode, parPatientType, parMsCode, manageYear)  from QuotaManage qm where qm.parMsCode = :parMsCode  " ;
		List<QuotaManage> listDrgQuotamanaeData = getRepository().createJpqlQuery(jpql).addParameter("parMsCode", parMsCode).list() ;
		return listDrgQuotamanaeData ;
	}


	@Override
	public List<Map<String, Object>> findQuotaManageByparMsCode(String parMsCode) {
		StringBuffer sql = new StringBuffer() ;
		sql.append(" select distinct ms.ms_code from drgs.t_managesummary ms \n") ;
		sql.append(" where ms.ms_code like '"+parMsCode+"%' \n") ;
		List<Map<String, Object>> resultList = jdbcTemplateObj.queryForList(sql.toString()) ;
		return resultList;
	}


	@Override
	public List<String> getOtherHspManageYears(String parMsCode) {
		String sql = "select distinct md.std_year from drgs.t_managesummarydtl md where md.par_ms_code = :parMsCode " ;
		List<String> list  = getRepository().createSqlQuery(sql).addParameter("parMsCode", parMsCode).list() ;
		return list;
	}

/**
 *  @Description：保存全院各指标管理目标值
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.application.QuotaManageApplication#saveHospManager(com.dhcc.DRGsHosp.core.domain.QuotaManage)
 */
	@Override
	public void saveHospManager(String parMscode, String year, String quotaCode, double bvalue) {
		if(bvalue>0) {
			String sql="declare cnt INTEGER;\r\n" + 
					"begin\r\n" + 
					" SELECT count(1) into cnt FROM DRGS.t_Quotamanage t where t.pardep_code is null and t.pardepgroup_code is null  and t.pardrg_code is null and t.par_ms_code='"+parMscode+"' and t.parquota_code='"+quotaCode+"' and t.manage_year='"+year+"';  \r\n" + 
					"if cnt = 0 then\r\n" + 
					"insert into drgs.t_quotamanage (qm_id,parquota_code,manage_benchmark,par_ms_code,manage_year) values(sys_guid(),'"+quotaCode+"',"+bvalue+",'"+parMscode+"','"+year+"');\r\n" + 
					"else\r\n" + 
					" update drgs.t_quotamanage  set manage_benchmark="+bvalue+" where pardep_code is null and pardepgroup_code is null  and pardrg_code is null and par_ms_code='"+parMscode+"' and parquota_code='"+quotaCode+"' and manage_year='"+year+"'; \r\n" + 
					"end if;\r\n" + 
					"commit;\r\n" + 
					"end;";
			jdbcTemplateObj.execute(sql);
		}
	}

/**
 *  @Description：保存科室组各指标管理目标值
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.application.QuotaManageApplication#saveDepGroupManager(java.lang.String, java.lang.String, java.lang.String, java.lang.String, double)
 */
@Override
public void saveDepGroupManager(String depGroupCode, String parMscode, String year, String quotaCode, double bvalue) {
	if(bvalue>0) {
		String sql="declare cnt INTEGER;\r\n" + 
				"begin\r\n" + 
				" SELECT count(1) into cnt FROM DRGS.t_Quotamanage t where t.pardep_code is null and t.pardepgroup_code ='"+depGroupCode+"'  and t.pardrg_code is null and t.par_ms_code='"+parMscode+"' and t.parquota_code='"+quotaCode+"' and t.manage_year='"+year+"';  \r\n" + 
				"if cnt = 0 then\r\n" + 
				"insert into drgs.t_quotamanage (pardepgroup_code,qm_id,parquota_code,manage_benchmark,par_ms_code,manage_year) values('"+depGroupCode+"',sys_guid(),'"+quotaCode+"',"+bvalue+",'"+parMscode+"','"+year+"');\r\n" + 
				"else\r\n" + 
				" update drgs.t_quotamanage  set manage_benchmark="+bvalue+" where pardep_code is null and pardepgroup_code ='"+depGroupCode+"'  and pardrg_code is null and par_ms_code='"+parMscode+"' and parquota_code='"+quotaCode+"' and manage_year='"+year+"'; \r\n" + 
				"end if;\r\n" + 
				"commit;\r\n" + 
				"end;";
		jdbcTemplateObj.execute(sql);
	}
}

/**
 * 
 *  @Description：保存科室各指标管理目标值
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.application.QuotaManageApplication#saveDepManager(java.lang.String, java.lang.String, java.lang.String, java.lang.String, double)
 */
@Override
public void saveDepManager(String depCode, String parMscode, String year, String quotaCode, double bvalue) {
	if(bvalue>0) {
		String sql="declare cnt INTEGER;\r\n" + 
				"begin\r\n" + 
				" SELECT count(1) into cnt FROM DRGS.t_Quotamanage t where t.pardepgroup_code  is null and t.pardep_code='"+depCode+"'  and t.pardrg_code is null and t.par_ms_code='"+parMscode+"' and t.parquota_code='"+quotaCode+"' and t.manage_year='"+year+"';  \r\n" + 
				"if cnt = 0 then\r\n" + 
				"insert into drgs.t_quotamanage (pardep_code,qm_id,parquota_code,manage_benchmark,par_ms_code,manage_year) values('"+depCode+"',sys_guid(),'"+quotaCode+"',"+bvalue+",'"+parMscode+"','"+year+"');\r\n" + 
				"else\r\n" + 
				" update drgs.t_quotamanage  set manage_benchmark="+bvalue+" where pardepgroup_code is null and pardep_code ='"+depCode+"'  and pardrg_code is null and par_ms_code='"+parMscode+"' and parquota_code='"+quotaCode+"' and manage_year='"+year+"'; \r\n" + 
				"end if;\r\n" + 
				"commit;\r\n" + 
				"end;";
		jdbcTemplateObj.execute(sql);
	}
	
}
/**
 *  @Description：保存全院drg病组绩效
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.application.QuotaManageApplication#saveDrgManager(java.lang.String, java.lang.String, java.lang.String, java.lang.String, double)
 */

@Override
public void saveDrgManager(String drgCode, String parMscode, String year, String quotaCode, double bvalue) {
	if(bvalue>0) {
		String sql="declare cnt INTEGER;\r\n" + 
				"begin\r\n" + 
				" SELECT count(1) into cnt FROM DRGS.t_Quotamanage t where t.pardepgroup_code  is null and t.pardrg_code='"+drgCode+"'  and t.pardep_code is null and t.par_ms_code='"+parMscode+"' and t.parquota_code='"+quotaCode+"' and t.manage_year='"+year+"';  \r\n" + 
				"if cnt = 0 then\r\n" + 
				"insert into drgs.t_quotamanage (pardrg_code,qm_id,parquota_code,manage_benchmark,par_ms_code,manage_year) values('"+drgCode+"',sys_guid(),'"+quotaCode+"',"+bvalue+",'"+parMscode+"','"+year+"');\r\n" + 
				"else\r\n" + 
				" update drgs.t_quotamanage  set manage_benchmark="+bvalue+" where pardepgroup_code is null and pardrg_code ='"+drgCode+"'  and  pardep_code is null and par_ms_code='"+parMscode+"' and parquota_code='"+quotaCode+"' and manage_year='"+year+"'; \r\n" + 
				"end if;\r\n" + 
				"commit;\r\n" + 
				"end;";
		jdbcTemplateObj.execute(sql);
	}
	
}
/**
 *  @Description：保存科室下的病组
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.application.QuotaManageApplication#saveDepDrgManager(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, double)
 */

@Override
public void saveDepDrgManager(String drgCode, String depCode, String parMscode, String year, String quotaCode, double bvalue) {
	if(bvalue>0) {
		String sql="declare cnt INTEGER;\r\n" + 
				"begin\r\n" + 
				" SELECT count(1) into cnt FROM DRGS.t_Quotamanage t where t.pardepgroup_code  is null and t.pardrg_code='"+drgCode+"'  and t.pardep_code ='"+depCode+"' and t.par_ms_code='"+parMscode+"' and t.parquota_code='"+quotaCode+"' and t.manage_year='"+year+"';  \r\n" + 
				"if cnt = 0 then\r\n" + 
				"insert into drgs.t_quotamanage (pardep_code,pardrg_code,qm_id,parquota_code,manage_benchmark,par_ms_code,manage_year) values('"+depCode+"','"+drgCode+"',sys_guid(),'"+quotaCode+"',"+bvalue+",'"+parMscode+"','"+year+"');\r\n" + 
				"else\r\n" + 
				" update drgs.t_quotamanage  set manage_benchmark="+bvalue+" where pardepgroup_code is null and pardrg_code ='"+drgCode+"'  and  pardep_code ='"+depCode+"' and par_ms_code='"+parMscode+"' and parquota_code='"+quotaCode+"' and manage_year='"+year+"'; \r\n" + 
				"end if;\r\n" + 
				"commit;\r\n" + 
				"end;";
		jdbcTemplateObj.execute(sql);
	}
}
/**
 *  @Description：全院其他机构绩效管理值导入
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.application.QuotaManageApplication#saveOtherManager(java.lang.String, java.lang.String, java.lang.String, double)
 */

@Override
public void saveOtherManager(String parMscode, String year, String quotaCode, double bvalue) {
	if(bvalue>0) {
		String sql="declare cnt INTEGER;\r\n" +
				"begin\r\n" +
				" SELECT count(1) into cnt FROM DRGS.t_Quotamanage t where t.pardepgroup_code  is null  and t.pardep_code is null and t.par_ms_code='"+parMscode+"' and t.parquota_code='"+quotaCode+"' and t.manage_year='"+year+"';  \r\n" +
				"if cnt = 0 then\r\n" +
				"insert into drgs.t_quotamanage (qm_id,parquota_code,manage_benchmark,par_ms_code,manage_year) values(sys_guid(),'"+quotaCode+"',"+bvalue+",'"+parMscode+"','"+year+"');\r\n" +
				"else\r\n" +
				" update drgs.t_quotamanage  set manage_benchmark="+bvalue+" where pardepgroup_code is null  and  pardep_code is null and par_ms_code='"+parMscode+"' and parquota_code='"+quotaCode+"' and manage_year='"+year+"'; \r\n" +
				"end if;\r\n" +
				"commit;\r\n" +
				"end;";
		jdbcTemplateObj.execute(sql);
	}
}
/**
 *  @Description：外院标杆导入
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.application.QuotaManageApplication#saveOutStd(java.lang.String, java.lang.String, java.lang.String, java.lang.String, double)
 */

@Override
public void saveOutStd(String year, String quotaCode, String drgCode, String parMscode, double bvalue) {
	if(bvalue>0) {
		String sql="declare cnt integer;\r\n" + 
				"begin \r\n" + 
				"select count(1) into cnt from drgs.t_managesummarydtl a where a.par_ms_code='"+parMscode+"' and a.parquota_code='"+quotaCode+"' and a.pardrg_code ='"+drgCode+"' and a.std_year='"+year+"';\r\n" + 
				"if cnt=0 then\r\n" + 
				"insert into drgs.t_managesummarydtl(msdtl_id,par_ms_code,parquota_code,pardrg_code,std_year,manage_benchmark)values(sys_guid(),'"+parMscode+"','"+quotaCode+"','"+drgCode+"','"+year+"',"+bvalue+");\r\n" + 
				"else \r\n" + 
				"update drgs.t_managesummarydtl set manage_benchmark="+bvalue+"  where par_ms_code='"+parMscode+"' and parquota_code='"+quotaCode+"'  and pardrg_code ='"+drgCode+"' and std_year='"+year+"';\r\n" + 
				"end if;\r\n" + 
				"commit;\r\n" + 
				"end;";
		jdbcTemplateObj.execute(sql);
	}
  }
}
